package com.tancire.question.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Resource;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tancire.common.enums.PurseStatus;
import com.tancire.common.exception.question.TrainException;
import com.tancire.common.utils.DateUtils;
import com.tancire.common.utils.StringUtils;
import com.tancire.member.domain.Member;
import com.tancire.member.domain.MemberPurse;
import com.tancire.member.domain.MemberTrainActivity;
import com.tancire.member.domain.MemberTrainAward;
import com.tancire.member.service.IMemberPurseService;
import com.tancire.member.service.IMemberService;
import com.tancire.member.service.IMemberTrainActivityService;
import com.tancire.member.service.IMemberTrainAwardService;
import org.springframework.stereotype.Service;
import com.tancire.question.mapper.TrainActivityMapper;
import com.tancire.question.domain.TrainActivity;
import com.tancire.question.service.ITrainActivityService;

/**
 * 答题活动Service业务层处理
 *
 * @author tancire
 * @date 2024-10-10
 */
@Service
public class TrainActivityServiceImpl implements ITrainActivityService {

    @Resource
    private TrainActivityMapper trainActivityMapper;

    @Resource
    private IMemberTrainActivityService memberTrainActivityService;

    @Resource
    private IMemberTrainAwardService memberTrainAwardService;

    @Resource
    private IMemberPurseService memberPurseService;

    @Resource
    private IMemberService memberService;

    /**
     * 查询答题活动
     *
     * @param id 答题活动主键
     * @return 答题活动
     */
    @Override
    public TrainActivity selectTrainActivityById(Long id) {
        return trainActivityMapper.selectTrainActivityById(id);
    }

    /**
     * 查询答题活动列表
     *
     * @param trainActivity 答题活动
     * @return 答题活动
     */
    @Override
    public List<TrainActivity> selectTrainActivityList(TrainActivity trainActivity) {
        return trainActivityMapper.selectTrainActivityList(trainActivity);
    }

    /**
     * 新增答题活动
     *
     * @param trainActivity 答题活动
     * @return 结果
     */
    @Override
    public int insertTrainActivity(TrainActivity trainActivity) {
        trainActivity.setCreateTime(DateUtils.getNowDate());
        return trainActivityMapper.insertTrainActivity(trainActivity);
    }

    /**
     * 修改答题活动
     *
     * @param trainActivity 答题活动
     * @return 结果
     */
    @Override
    public int updateTrainActivity(TrainActivity trainActivity) {
        trainActivity.setUpdateTime(DateUtils.getNowDate());
        return trainActivityMapper.updateTrainActivity(trainActivity);
    }

    /**
     * 批量删除答题活动
     *
     * @param ids 需要删除的答题活动主键
     * @return 结果
     */
    @Override
    public int deleteTrainActivityByIds(Long[] ids) {
        return trainActivityMapper.deleteTrainActivityByIds(ids);
    }

    /**
     * 删除答题活动信息
     *
     * @param id 答题活动主键
     * @return 结果
     */
    @Override
    public int deleteTrainActivityById(Long id) {
        return trainActivityMapper.deleteTrainActivityById(id);
    }

    /**
     * 获取排行榜
     * todo 做完排行榜基础功能再加
     *
     * @return
     */
    @Override
    public List<Member> getRankingList() {
        return new ArrayList<>();
    }

    /**
     * 处理答题结果
     *
     * @param id
     */
    @Override
    public void handleActivityResult(Long id) {
        TrainActivity trainActivity = this.trainActivityMapper.selectTrainActivityById(id);
        Integer settlementStatus = trainActivity.getSettlementStatus();
        if (null != settlementStatus && 1 == settlementStatus) {
            throw new TrainException("活动已经处理，不能重复处理");
        } else {
            TrainActivity updateActivity = new TrainActivity();
            updateActivity.setId(trainActivity.getId());
            updateActivity.setSettlementStatus(1);
            this.trainActivityMapper.updateTrainActivity(updateActivity);
        }
        Date activityEnd = trainActivity.getActivityEnd();
        long endTime = activityEnd.getTime();
        if (endTime > System.currentTimeMillis()) {
            throw new TrainException("活动未结束，结束后才能处理答题结果");
        }
        // 查询答题结果
        MemberTrainActivity query = new MemberTrainActivity();
        query.setActivityId(id);
        query.setAttendStatus(1);
        List<MemberTrainActivity> memberTrainActivityList = this.memberTrainActivityService.selectMemberTrainActivityList(query);
        if (ObjectUtil.isNotEmpty(memberTrainActivityList)) {
            List<MemberTrainActivity> topMemberList = memberTrainActivityList.stream()
                    .filter(x -> null != x.getStartTime() && null != x.getUseTime())
                    .sorted(Comparator.comparing(MemberTrainActivity::getUseTime))
                    .collect(Collectors.toList());

            if (ObjectUtil.isNotEmpty(topMemberList)) {
                for (int i = 0; i < topMemberList.size(); i++) {
                    MemberTrainActivity memberTrainActivity = topMemberList.get(i);
                    // 初始化要保存的精品信息
                    MemberTrainAward memberTrainAward = new MemberTrainAward();
                    memberTrainAward.setMemberId(memberTrainActivity.getMemberId());
                    memberTrainAward.setActivityId(trainActivity.getId());
                    memberTrainAward.setActivityName(trainActivity.getActivityName());
                    memberTrainAward.setAwardCode(IdUtil.getSnowflakeNextId() + "");
                    memberTrainAward.setAwardLevel((i + 1) + "");
                    memberTrainAward.setAwardStatus(0);
                    int levelNum = 10;
                    if (i == 0) {
                        memberTrainAward.setAwardContent(trainActivity.getGoldAwardName());
                        levelNum = 60;
                    } else if (i == 1) {
                        memberTrainAward.setAwardContent(trainActivity.getSilverAwardName());
                        levelNum = 30;
                    } else if (i == 2) {
                        memberTrainAward.setAwardContent(trainActivity.getBronzeAwardName());
                        levelNum = 10;
                    }
                    if (!StringUtils.isBlank(memberTrainAward.getAwardCode())) {
                        this.memberTrainAwardService.insertMemberTrainAward(memberTrainAward);
                        Member member = memberService.selectMemberByMemberId(memberTrainActivity.getMemberId());
                        Member upMember = new Member();
                        upMember.setMemberId(member.getMemberId());
                        Integer memberLevel = member.getMemberLevel();
                        if (null == memberLevel) {
                            memberLevel = 0;
                        }
                        upMember.setMemberLevel(memberLevel + levelNum);
                        this.memberService.updateMember(upMember);
                    }
                }
            }
            // 循环处理其他积分金币奖励
            for (MemberTrainActivity memberTrainActivity : memberTrainActivityList) {
                Long memberId = memberTrainActivity.getMemberId();
                // 查询钱包信息
                MemberPurse memberPurse = this.memberPurseService.selectMemberPurseByMemberId(memberId);
                Member member = memberService.selectMemberByMemberId(memberId);
                if (null == memberPurse) {
                    memberPurse = new MemberPurse();
                    memberPurse.setMemberId(memberId);
                    memberPurse.setMemberAccount(member.getAccount());
                    memberPurse.setCoinNum(new BigDecimal("20"));
                    memberPurse.setPurseStatus(PurseStatus.NORMAL.getCode());
                    this.memberPurseService.insertMemberPurse(memberPurse);
                } else {
                    String purseStatus = memberPurse.getPurseStatus();
                    if (PurseStatus.NORMAL.getCode().equals(purseStatus)) {
                        BigDecimal coinNum = memberPurse.getCoinNum();
                        if (null == coinNum) {
                            coinNum = BigDecimal.ZERO;
                        }
                        coinNum = coinNum.add(new BigDecimal("20"));
                        // 更新金额会有重复操作情况，后期进行优化
                        MemberPurse update = new MemberPurse();
                        update.setId(memberPurse.getId());
                        update.setCoinNum(coinNum);
                        this.memberPurseService.updateMemberPurse(update);
                    }
                }
                // 加经验
                Member upMember = new Member();
                upMember.setMemberId(member.getMemberId());
                Integer memberLevel = member.getMemberLevel();
                if (null == memberLevel) {
                    memberLevel = 0;
                }
                upMember.setMemberLevel(memberLevel + 2);
                this.memberService.updateMember(upMember);

            }
        }

    }
}
